<?php
/**
 * 校验用户登录
 * ============================================================================
 * * 版权所有 度拉拉 * *
 * 网站地址: http://www.dlltrip.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author By: 倪宗锋
 * PhpStorm LoginController.php
 * Create By 2017/6/7 17:34 $
 */

namespace zzcx\controllers\user;

use common\models\FxUser;
use common\models\FxUserOpenid;
use common\service\geetest\GeetestService;
use common\service\login\LoginService;
use common\service\WeChatService;
use common\util\Util;
use yii\web\Controller;
use zzcx\service\user\Login;

class LoginController extends Controller
{
    private $service = null;

    public function service()
    {
        if ($this->service == null) {
            $this->service = new Login();
        }
        return $this->service;
    }

    /**
     * Des:校验是否登录
     * Name: actionCheckLogin
     * @return string
     * @author 倪宗锋
     */
    public function actionCheckLogin()
    {
        $checkLogin = LoginService::checkLogin();
        return json_encode($checkLogin);
    }

    /**
     * Des:未登录用户通过该地址进行登录
     * Name: actionLogin
     * @return string|\yii\web\Response
     * @author 倪宗锋
     */
    public function actionLogin()
    {
        $this->viewPath = ROOT_PATH . "/web/public/html";
        $this->view->defaultExtension = 'phtml';
        return $this->render('login');
    }

    /**
     * Des:发送短信验证码
     * Name: actionSendMsg
     * @return string
     * @author 倪宗锋
     */
    public function actionSendMsg()
    {
        return Util::returnJsSu('验证码发送成功');
    }

    /**
     * Des:发送短信验证码
     * Name: actionSendMsg
     * @return array
     * @author 倪宗锋
     */
    public function actionSendLoginMsg()
    {
        $gt = new GeetestService();
        $gee_challenge = $this->_post('geetest_challenge', '');
        $gee_validate = $this->_post('geetest_validate', '');
        $gee_sec_code = $this->_post('geetest_seccode', '');
        $return = $gt->checkGee($gee_challenge, $gee_validate, $gee_sec_code);//控件校验
        if ($return['flag'] == false) {//如果校验失败
            return json_encode($return);
        }
        $phone = $this->_post('phone', '');
        $return = $this->service()->sendMessage($phone);
        return json_encode($return);
    }

    /**
     * Des:登录处理、提交
     * Name: actionDoLogin
     * @return array
     * @author 倪宗锋
     */
    public function actionDoLogin()
    {
        $param = [
            'phone' => $this->_post('phone', ''),//手机号
            'code' => $this->_post('code', ''),//验证码
        ];
        $return = $this->service()->doLogin($param);
        return json_encode($return);
    }

    /**
     * Des:设置微信或者ali登录
     * Name: actionSetLogin
     * @return \yii\web\Response
     * @author 倪宗锋
     */
    public function actionSetLogin()
    {
        $code = $this->_get('code', '');
        $redirect = $this->_get('redirect', '/');
        $getAppType = Util::checkWeChatOrAliPay();
        $getToken = LoginService::getToken($code, $getAppType);
        if ($getToken['flag'] == true) {
            $key = Util::getSiteConfig()['entryAuthWeChat'];
            setcookie($key.'_openid', $getToken['data']['openid'], time() + 3600000, "/");//保存openid在cookies中 用于微信吊起支付
        }
        return $this->redirect($redirect);
    }

    /**
     * Des:菜单跳转
     * Name: actionMenuUrl
     * @return \yii\web\Response
     * @author 倪宗锋
     */
    public function actionMenuUrl()
    {
        $redirect = $this->_get('redirect', '/');
        $getUrl = LoginService::getLoginUrlUnAuth($redirect, 1);
        return $this->redirect($getUrl);
    }

    /**
     * Des:绑定分销用户
     * Name: actionBindFxUser
     * @author 倪宗锋
     */
    public function actionBindFxUser()
    {
        $redirect = $this->_get('redirect', '/');
        $fx_uid = intval($this->_get('fx_uid', ''));
        $key = Util::getSiteConfig()['entryAuthWeChat'];
        if (empty($_COOKIE[$key.'_openid'])) {
            $siteConfig = Util::getSiteConfig();
            $return_url = $siteConfig['host_name'] . '/zzcx/user/login/bind-fx-user?fx_uid=' . $fx_uid . '&redirect=' . urlencode($redirect);
            $getUrl = LoginService::getLoginUrlUnAuth($return_url, 1);
            return $this->redirect($getUrl);
        } else {
            $fx_user = new FxUser();
            $data = ['wx_openid' => $_COOKIE[$key.'_openid']];
            $fx_user->updateById($data, $fx_uid);
            return $this->redirect($redirect);
        }
    }

    public function actionTest()
    {
        //获取tcp协议号码。
        $tcp = getprotobyname("tcp");
        // 建立server端socket ，创建并返回一个套接字，也称作一个通讯节点。一个典型的网络连接由 2 个套接字构成，一个运行在客户端，另一个运行在服务器端。
        $socket = socket_create(AF_INET, SOCK_STREAM, $tcp);
        //绑定要监听的ip和端口，这里绑定的ip一定要写局域网ip，写成127.0.0.1客户端将无法与服务端建议连接。
        socket_bind($socket, '192.168.6.199', 10008);
        //监听端口
        socket_listen($socket);
        //初始化一个数据，和客户端通信
        $buffer = "connect";
        while (true) {
            // 接受客户端请求过来的一个socket连接
            $connection = socket_accept($socket);
            if (!$connection) {
                echo "connect faild";
            } else {
                echo "Socket connected\n";
                // 向客户端传递一个信息数据
                if ($buffer != "") {
                    echo "send data to client\n";
                    socket_write($connection, $buffer . "\n");
                    echo "Wrote to socket\n";
                } else {
                    echo "no data in the buffer\n";
                }
                // 从客户端获取得的数据
                while ($data = @socket_read($connection, 1024, PHP_NORMAL_READ)) {
                    printf("Buffer: " . $data . "\n");
                    //取得信息给客户端一个反馈, Thank you client, you data is  Received success发给客户端的回应信息。
                    socket_write($connection, "Thank you client, you data is  Received success\n");
                }
            }
            //关闭 socket
            socket_close($connection);
            printf("Closed the socket\n");
        }
    }

    public function actionGetFx()
    {
        $url = $this->_post('url');
        $srt = WeChatService::getSignPackage($url);
        return json_encode($srt);
    }

    /**
     * Des:初始化控件数据
     * Name: actionStartGee
     * @return string
     * @author 倪宗锋
     */
    public function actionStartGee()
    {
        $GtSdk = new GeetestService();
        session_start();
        $data = array(
            "user_id" => time(), # 网站用户id
            "client_type" => "h5", #web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
            "ip_address" => "127.0.0.1" # 请在此处传输用户请求验证时所携带的IP
        );
        $status = $GtSdk->pre_process($data, 1);
        $_SESSION['gtserver'] = $status;
        $_SESSION['user_id'] = $data['user_id'];
        $return = $GtSdk->get_response_str();
        return Util::returnJsSu('', json_decode($return));
    }

    /**
     * Des:校验数据
     * Name: actionCheckGee
     * @return string
     * @author 倪宗锋
     */
    public function actionCheckGee()
    {
        $gt = new GeetestService();
        $geetest_challenge = $this->_post('geetest_challenge', '');
        $geetest_validate = $this->_post('geetest_validate', '');
        $geetest_seccode = $this->_post('geetest_seccode', '');
        $return = $gt->checkGee($geetest_challenge, $geetest_validate, $geetest_seccode);
        return json_encode($return);
    }
    /*
     * 第三方授权路径
     */
    public function actionAuthLogin()
    {
        $code = $this->_get('code', '');
        if (empty($code)) {
            $code = $this->_get('auth_code', '');
        }
        $url = $this->_get('redirect', '');
//        $url = $url;
        $url .= '&code=' . $code;
        header('location:' . $url);
        return $url;
    }
}